import request from '@/utils/request'
var TANGER_OCX_OBJ
var ntkoBrowser
var paramsObj
var IsFileOpened = false
var svrmod = '.jsp'
var serverurl = 'http://192.168.5.244:7160/DapREST/'

var openurl = serverurl + 'server/OpenFromServerDir' + svrmod + '?filename=test.doc'
var saveurl = serverurl + 'server/SaveToServerDir' + svrmod
export default {
  // 32位控件的classid
  classid: 'clsid:A64E3073-2016-4baf-A89D-FFE1FAA10EC2',
  // 64位控件的calssid
  classidx64: 'clsid:A64E3073-2016-4baf-A89D-FFE1FAA10EE2',
  // 谷歌和火狐的classid
  chfixclassid: '{A64E3073-2016-4baf-A89D-FFE1FAA10EE2}',
  // 32位控件包的路径
  codebase: 'officecontrol/ofctnewclsid.cab#version=6,0,1,0',
  // 64位控件包的路径
  codebase64: 'officecontrol/ofctnewclsidx64.cab#version=6,0,1,0',
  // 设置高度
  height: '100%',
  // 设置宽度
  width: '100%',
  // 买断授权密钥如果不是买断可以不用写
  MakerCaption: '上海数慧系统技术有限公司',
  // 买断授权密钥如果不是买断可以不用写
  MakerKey: 'AB377D79A7F9A3BCF2E49CBB5210CC1F2DCE04AD',
  // 密钥
  ProductCaption: '上海数慧系统技术有限公司某某测试用户',
  // 密钥
  ProductKey: '4E4775D17680C526CAA61114667576520CCA4477',
  // 解除时间密钥
  NoExpireKey: '4BBA1B53B15206E78D33846E1420A67B',
  // 插件密钥
  BrowserProductKey: 'D1A445FEECDC83E774C4D3A22C267596661F55B5',

  // 设置ntko控件对象
  SetNtkoObj: function (obj, ntkob, params) {
    TANGER_OCX_OBJ = obj
    ntkoBrowser = ntkob
    for (var d in params) {
        if (params[d] === 'true' || params[d] === 'false') {
          params[d] = JSON.parse(params[d])
        }
    }
    paramsObj = params
  },

  // 打开文件通过下载url
  OpenFileByUrl: function () {
    TANGER_OCX_OBJ.Menubar = false
    TANGER_OCX_OBJ.TitleBar = false
    TANGER_OCX_OBJ.isShowFullScreenButton = false // 屏蔽全屏按钮
    TANGER_OCX_OBJ.FileSave = false
    TANGER_OCX_OBJ.FileSaveAs = true

    // 下载文件请求
    var urlSrc = window.config.VUE_APP_BASE_URL + 'materialInst/file/download?materialFileId=' + paramsObj.materialId
    var reportUrlSrc = window.config.VUE_APP_BASE_URL + 'projectReport/downloadWordReport?projectId=' + paramsObj.projectId + '&revisionId=' + paramsObj.revisionId
    var saveurl = window.config.VUE_APP_BASE_URL + 'projectMaterial/material/update?materialId=' + paramsObj.materialId + '&projectId=' + paramsObj.projectId
    if (paramsObj.type == 'report') {
      paramsObj.urlSrc = reportUrlSrc
    } else {
      paramsObj.urlSrc = urlSrc
    }
    paramsObj.saveurl = saveurl

    // linux需要传ProgID
    var ProgID = ''
    if (paramsObj.fileExt) {
      switch (paramsObj.fileExt.toLowerCase()) {
        case '.docx':
        case '.doc':
          paramsObj.isWord = true
          ProgID = 'Word.Document'
          break
        case '.xls':
        case '.xlsx':
          ProgID = 'Excel.Sheet'
          break
        default:
          paramsObj.isWord = false
          ProgID = 'Word.Document'
      }
    }
    if (window.navigator.platform.indexOf('Linux') > -1) {
      TANGER_OCX_OBJ.OpenFromURL(paramsObj.urlSrc, paramsObj.readOnly, ProgID)
    } else {
      TANGER_OCX_OBJ.OpenFromURL(paramsObj.urlSrc, paramsObj.readOnly)
    }
  },

  // 添加ntko监听
  AddNtkoEvent: function (eventName, method) {
    var scriptStr = document.createElement('script')
    scriptStr.setAttribute('for', 'TANGER_OCX')
    scriptStr.event = eventName
    scriptStr.appendChild(document.createTextNode('activeXListener.' + method))
    document.body.appendChild(scriptStr)
    window.activeXListener = this
  },

  // 新建文档
  // word-->Word.Document\Wps.Document
  // excel-->Excel.Sheet
  CreateNewOffice: function (progid) {
    TANGER_OCX_OBJ.CreateNew(progid)
  },

  // 删除左右两端的空格
  trim: function (str) {
    return str.replace(/(^\s*)|(\s*$)/g, '')
  },

  // 文档禁止编辑
  SetDocReadOnly: function () {
    try {
      if (TANGER_OCX_OBJ.DocType == 1 || TANGER_OCX_OBJ.DocType == 6) {
        TANGER_OCX_OBJ.ActiveDocument.Protect(1, true, 'password')
      } else if (TANGER_OCX_OBJ.DocType == 2) {
        TANGER_OCX_OBJ.ActiveDocument.Protect('password')
        for (var i = 1; i <= TANGER_OCX_OBJ.ActiveDocument.Sheets.Count; i++) {
          TANGER_OCX_OBJ.ActiveDocument.Sheets(i).Protect('password', true, true, true, true)
        }
      } else {
        TANGER_OCX_OBJ.ShowTipMessage('提示', '不允许设置只读.')
      }
    } catch (err) {
      // alert("错误" + err.description);
    }
  },

  // 文档允许编辑
  UnSetReadOnly: function () {
    try {
      if (TANGER_OCX_OBJ.DocType == 1 || TANGER_OCX_OBJ.DocType == 6) {
        TANGER_OCX_OBJ.ActiveDocument.UnProtect('password')
      } else if (TANGER_OCX_OBJ.DocType == 2) {
        for (var i = 1; i <= TANGER_OCX_OBJ.ActiveDocument.Sheets.Count; i++) {
          TANGER_OCX_OBJ.ActiveDocument.Sheets(i).Unprotect('password')
        }
        TANGER_OCX_OBJ.ActiveDocument.application.ActiveWorkbook.Unprotect('password')
      } else {
        TANGER_OCX_OBJ.ShowTipMessage('提示', '不允许设置允许编辑.')
      }
    } catch (err) {
      // alert("错误" + err.description);
    }
  },

  // 是否显示工具栏等
  IsShowToolBar: function () {
    TANGER_OCX_OBJ.Toolbars = !TANGER_OCX_OBJ.Toolbars
    TANGER_OCX_OBJ.Titlebar = !TANGER_OCX_OBJ.Titlebar
    TANGER_OCX_OBJ.Statusbar = !TANGER_OCX_OBJ.Statusbar
    TANGER_OCX_OBJ.Menubar = !TANGER_OCX_OBJ.Menubar
    TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.DocumentMap = !TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.DocumentMap // 隐藏导航窗格
    TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.ActivePane.DisplayRulers = !TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.ActivePane.DisplayRulers // 隐藏标尺
    TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.DocumentMap = false // 隐藏左侧导航格
  },

  // 菜单栏项灰色
  MenubarShowGray: function () {
    TANGER_OCX_OBJ.FileOpen = !TANGER_OCX_OBJ.FileOpen
    TANGER_OCX_OBJ.FileClose = !TANGER_OCX_OBJ.FileClose
    TANGER_OCX_OBJ.FilePageSetup = !TANGER_OCX_OBJ.FilePageSetup
    TANGER_OCX_OBJ.FilePrint = !TANGER_OCX_OBJ.FilePrint
    TANGER_OCX_OBJ.FilePrintPreview = !TANGER_OCX_OBJ.FilePrintPreview
  },

  // 自定义工具栏功能
  ShowCutomToolBar: function (isshow) {
    if (isshow) {
      if (window.navigator.platform.indexOf('Linux') > -1) {
          TANGER_OCX_OBJ.AddCustomToolButton('保存', 5, 0)
          TANGER_OCX_OBJ.AddCustomToolButton('另存为', 5, 1)

          TANGER_OCX_OBJ.AddCustomToolButton('打开修订', -1, 2)
          TANGER_OCX_OBJ.AddCustomToolButton('关闭修订', -1, 3)
          TANGER_OCX_OBJ.AddCustomToolButton('接受修订', -1, 4)
          TANGER_OCX_OBJ.AddCustomToolButton('接受并保存', -1, 5)

          TANGER_OCX_OBJ.AddCustomToolButton('显示痕迹', -1, 6)
          TANGER_OCX_OBJ.AddCustomToolButton('隐藏痕迹', -1, 7)
          TANGER_OCX_OBJ.AddCustomToolButton('套红头', -1, 8)
          TANGER_OCX_OBJ.AddCustomToolButton('打印', 9, 9)
          TANGER_OCX_OBJ.AddCustomToolButton('打印预览', 10, 10)
          TANGER_OCX_OBJ.AddCustomToolButton('退出打印预览', 10, 11)
          TANGER_OCX_OBJ.AddCustomToolButton('关闭', -1, 12)
      } else {
          TANGER_OCX_OBJ.AddCustomToolButton('保存', 5)
          TANGER_OCX_OBJ.AddCustomToolButton('另存为', 5)

          TANGER_OCX_OBJ.AddCustomToolButton('打开修订', -1)
          TANGER_OCX_OBJ.AddCustomToolButton('关闭修订', -1)
          TANGER_OCX_OBJ.AddCustomToolButton('接受修订', -1)
          TANGER_OCX_OBJ.AddCustomToolButton('接受并保存', -1)

          TANGER_OCX_OBJ.AddCustomToolButton('显示痕迹', -1)
          TANGER_OCX_OBJ.AddCustomToolButton('隐藏痕迹', -1)
          TANGER_OCX_OBJ.AddCustomToolButton('套红头', -1)
          TANGER_OCX_OBJ.AddCustomToolButton('打印', 9)
          TANGER_OCX_OBJ.AddCustomToolButton('打印预览', 10)
          TANGER_OCX_OBJ.AddCustomToolButton('退出打印预览', 10)
          TANGER_OCX_OBJ.AddCustomToolButton('关闭', -1)
      }
      // 设置按钮显隐
      if (!paramsObj.readOnly) {
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(0, true, true)// 保存
        if (!paramsObj.saveAsBtn) {
          TANGER_OCX_OBJ.SetCustomToolButtonStatus(1, false, false)// 另存为
        }

        if (!(paramsObj.markingBtn || paramsObj.markBtn)) {
          TANGER_OCX_OBJ.SetCustomToolButtonStatus(2, false, false)// 打开修订
          TANGER_OCX_OBJ.SetCustomToolButtonStatus(3, false, false)// 关闭修订
          TANGER_OCX_OBJ.SetCustomToolButtonStatus(4, false, false)// 接受修订
          TANGER_OCX_OBJ.SetCustomToolButtonStatus(5, false, false)// 接受并保存
        }
        if (!paramsObj.isAddRedHead) {
          TANGER_OCX_OBJ.SetCustomToolButtonStatus(8, false, false)
        }
      } else {
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(0, false, false)// 保存
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(1, false, false)// 另存为
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(2, false, false)// 打开修订
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(3, false, false)// 关闭修订
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(4, false, false)// 接受修订
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(5, false, false)// 接受并保存
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(8, false, false)// 套红头
      }
      if (!paramsObj.revisionsBtn) {
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(6, false, false)// 显示痕迹
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(7, false, false)// 隐藏痕迹
      }
      if (!paramsObj.printBtn) {
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(9, false, false)// 打印
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(10, false, false)// 打印预览
        TANGER_OCX_OBJ.SetCustomToolButtonStatus(11, false, false)// 退出打印预览
      }

      TANGER_OCX_OBJ.SetCustomToolButtonStatus(12, true, true)// 关闭
      TANGER_OCX_OBJ.CustomToolBar = true
    } else {
      TANGER_OCX_OBJ.CustomToolBar = false
    }
  },

  // 痕迹保留
  SetReviewMode: function (flag, showMessage) {
    TANGER_OCX_OBJ.ActiveDocument.TrackRevisions = flag // 是否启动痕迹保留
    TANGER_OCX_OBJ.ActiveDocument.ShowRevisions = flag // 是否显示痕迹
    TANGER_OCX_OBJ.EnterRevisionMode(true)
    if (showMessage && flag) {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '已启动修订', false)
    }
    if (showMessage && !flag) {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '已关闭修订', false)
    }
  },

  // 接受或者取消所有修订
  TANGER_OCX_AllRevisions: function (flag) {
    if (flag) {
      TANGER_OCX_OBJ.ActiveDocument.AcceptAllRevisions() // 接受所有的痕迹修订
    } else {
      TANGER_OCX_OBJ.ActiveDocument.Application.WordBasic.RejectAllChangesInDoc() // 拒绝所有痕迹修订
    }
  },

  // 文件头套红
  insertRedHeadFromUrl: function (headFileURL) {
    TANGER_OCX_OBJ.AddTemplateFromURL(headFileURL)
  },

  // 获取全文内容
  getContent: function () {
    // 定义变量，存放内容
    var content = ''
    // 得到信息的段落数
    var curSel = TANGER_OCX_OBJ.ActiveDocument.Application.Selection
    curSel.WholeStory() // 选中全文
    content = curSel.Range.Text
    return content
  },

  // 保护文档部分修改    书签范围可以编辑
  protectPartDoc: function () {
    var marks = TANGER_OCX_OBJ.ActiveDocument.Bookmarks // 获取所有的书签
    for (var i = 1; i <= marks.Count; i++) {
      if (marks.Item(i).Name != 'biaoti') {
        TANGER_OCX_OBJ.ActiveDocument.Bookmarks.Item(i).Range.Select() // 选取书签区域保护
        TANGER_OCX_OBJ.ActiveDocument.Application.Selection.Editors.Add(-1) // 增加可编辑区域
        TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.View.ShadeEditableRanges = 0
        TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.View.ShowBookmarks = true
      }
    }
    if (TANGER_OCX_OBJ.ActiveDocument.ProtectionType == -1) {
      TANGER_OCX_OBJ.ActiveDocument.TrackRevisions = true // 是否启动痕迹保留
      TANGER_OCX_OBJ.ActiveDocument.ShowRevisions = true // 是否显示痕迹
      TANGER_OCX_OBJ.ActiveDocument.Protect(3, 0, 'password') // 实现文档保护
    }
  },

  // 自定义工具栏操作
  OnCustomToolBarCom (btnIdx) {
    if (btnIdx == 0) { // 保存
      this.save()
    } else if (btnIdx == 1) { // 另存为
      TANGER_OCX_OBJ.ShowDialog(3)
    } else if (btnIdx == 2) { // 打开修订
      this.SetReviewMode(true, true)
    } else if (btnIdx == 3) { // 关闭修订
      this.SetReviewMode(false, true)
    } else if (btnIdx == 4) { // 接受修订
      this.acceptMark(true)
    } else if (btnIdx == 5) { // 接受并保存
      this.acceptSave()
    } else if (btnIdx == 6) { // 显示痕迹
      if (!TANGER_OCX_OBJ.ActiveDocument.Application.ActiveWindow.View.ShowRevisionsAndComments) {
        try {
          TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.View.SplitSpecial = 18
        } catch (e) {}
        // wps处理逻辑
        try {
          TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.ActivePane.View.Zoom.PageFit = 18
        } catch (e) {}
        TANGER_OCX_OBJ.ActiveDocument.Application.ActiveWindow.View.ShowRevisionsAndComments = true
      }
    } else if (btnIdx == 7) { // 隐藏痕迹
      try {
        TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.View.SplitSpecial = 0
      } catch (e) {}
      // wps处理逻辑
      try {
        TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.ActivePane.View.Zoom.PageFit = 0
      } catch (e) {}
      TANGER_OCX_OBJ.ActiveDocument.Application.ActiveWindow.View.ShowRevisionsAndComments = false
      paramsObj.showRevisions = false
    } else if (btnIdx == 8) { // 套红头
      this.addRedHead()
    } else if (btnIdx == 9) { // 打印
      this.MyPrint()
    } else if (btnIdx == 10) { // 打印预览
      this.MyPrintPreview()
    } else if (btnIdx == 11) { // 退出打印预览
      this.MyExitPrintPreview()
    } else if (btnIdx == 12) { // 关闭
      if (!paramsObj.readOnly && !TANGER_OCX_OBJ.ActiveDocument.Saved) {
        var saveFile = TANGER_OCX_OBJ.ShowConfirmMessage('提示', '关闭前是否需要保存', false, true)
        if (saveFile) {
          if ((paramsObj.marking || paramsObj.mark) && paramsObj.isWord) { // 接受修订
            TANGER_OCX_OBJ.EnterRevisionMode(false)
            TANGER_OCX_OBJ.ActiveDocument.AcceptAllRevisions()
          }
          if (paramsObj.isWord) {
            TANGER_OCX_OBJ.EnterRevisionMode(false)
          }
          var msg = TANGER_OCX_OBJ.SaveToURL(paramsObj.saveurl, 'file', '', '', 0, true)
        }
      }
      window.opener = null
      window.open('', '_self')
      window.close()
    }
  },

  save: function () {
    if (!TANGER_OCX_OBJ.ActiveDocument.Saved) {
      var msg = TANGER_OCX_OBJ.SaveToURL(paramsObj.saveurl, 'file', '', '', 0, true)
      // if (browser == 'IE') {
      this.onDocSaved(null, null, msg)
      // }
    }
  },

  onDocSaved: function (a, b, msg) {
    // 编辑且是word默认留痕
    if (!paramsObj.readOnly && paramsObj.isWord) {
      TANGER_OCX_OBJ.EnterRevisionMode(true)
    }
    if (paramsObj.isWord) {
      TANGER_OCX_OBJ.ActiveDocument.Application.ActiveWindow.View.ShowRevisionsAndComments = false
    }
    var msg = eval('(' + msg + ')')
    if (msg.status == 'success' || msg) {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '保存成功', false)
    } else {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '保存失败', false)
    }
    TANGER_OCX_OBJ.ActiveDocument.saved = true
  },

  // 接受修订
  acceptMark: function (showMessage) {
    TANGER_OCX_OBJ.EnterRevisionMode(false)
    TANGER_OCX_OBJ.ActiveDocument.AcceptAllRevisions()
    if (showMessage) {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '已接受修订', false)
    }
  },

  // 接受修订
  acceptSave: function () {
    TANGER_OCX_OBJ.EnterRevisionMode(false)
    TANGER_OCX_OBJ.ActiveDocument.AcceptAllRevisions()
    this.save()
  },

  // 套红头
  addRedHead: function () {
    if (window.navigator.platform.indexOf('Linux') == -1) {
      TANGER_OCX_OBJ.ShowUIMessage('正在套红头')
    }
    var params = {
      projectId: paramsObj.projectId,
      materialId: paramsObj.materialId,
      userId: paramsObj.userId
    }
    var addRedHeadUrl = serverurl + '/st/interactionApprove/v1/addRedHead'
    alert(addRedHeadUrl)
    request({
      method: 'get',
      url: addRedHeadUrl,
      params: params
    }).then(d => {
      alert(d)
      var ntkoarry = new Array()
      ntkoarry.push(JSON.stringify(d))
      ntkoBrowser.ntkoSetReturnValueToParentPage('OnRefreshMatertialList', ntkoarry)
      if (window.navigator.platform.indexOf('Linux') == -1) {
        TANGER_OCX_OBJ.closeUIMessage()
      }
      window.location.href = window.location.href.replace(paramsObj.materialId, JSON.parse(d).data.id)
      window.postMessage('{"type":"refreshMatertialList"}', '*')
    }).catch((msg) => {

    })
  },

  // 打印文档
  MyPrint: function (selectprint) {
    if (IsFileOpened) {
      TANGER_OCX_OBJ.PrintOut(selectprint)
    } else {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '无文档打开不能执行打印！')
    }
  },

  // 打印预览文档
  MyPrintPreview: function () {
    if (IsFileOpened) {
      TANGER_OCX_OBJ.PrintPreview()
    } else {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '无文档打开不能执行打印预览！')
    }
  },

  // 退出打印预览文档
  MyExitPrintPreview: function () {
    TANGER_OCX_OBJ.ExitPrintPreview()
  },

  getUrl: function () {
    var pathName = window.location.href
    var varLength = pathName.lastIndexOf('/')
    var strURL = pathName.substr(0, varLength + 1)
    return strURL.replace('#', '')
  },

  getQueryString (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) { return unescape(r[2]) }
    return null
  },

  OnDocumentOpened (str, doc) {
    console.log('文档已打开')
    IsFileOpened = true
    // 自定义工具栏按钮，该功能可选
    this.ShowCutomToolBar(true)
    this.onDocOpened()
  },

  onDocOpened: function () {
    if ((paramsObj.markingBtn || paramsObj.markBtn) && paramsObj.isWord) {
        this.SetReviewMode()
    }
    TANGER_OCX_OBJ.WebUserName = paramsObj.userName
    // 编辑打开 默认打开修订 记录修改记录
    if (!paramsObj.readOnly) {
      this.UnSetReadOnly()
    } else {
      this.SetDocReadOnly()
    }
  },

  OnDocumentClosed (str, doc) {
    console.log('文档已关闭')
  },

  OnSaveToURL (code, data, html) {
    TANGER_OCX_OBJ.ShowTipMessage('提示', this.trim(html))
  },

  OnFileCommand (item) {
    console.log('FileCommand:' + item)
  },

  // Linux替换授权文件
  NtkoDownLoadCfgFile () {
    if (window.navigator.platform.indexOf('Linux') > -1) {
      if (TANGER_OCX_OBJ.NtkoCfgFileID == '{6D479692-1399-4229-A11A-7060167EF62D}') {

      } else {
        TANGER_OCX_OBJ.NtkoDownLoadCfgFile('officecontrol/ntkocfgfile.dat')
      }
    }
  },

/** -----------------------------以下未使用 开始-------------------------------------**/

  // 自定义菜单按钮
  AddButtonOnMenu: function () {
    if (window.navigator.platform.indexOf('Linux') > -1) {
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(1, '插入文字', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(2, '插入文字水印', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(3, '插入图片水印', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(4, '页面转word', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(5, '替换测试', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(6, '替换测试2', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(7, '删除水印', true)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(8, '关闭页面', true)
    } else {
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(1, '插入文字', true, 1, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(2, '插入文字水印', true, 2, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(3, '插入图片水印', true, 3, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(4, '页面转word', true, 4, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(5, '替换测试', true, 5, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(6, '替换测试2', true, 6, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(7, '删除水印', true, 7, 80)
      TANGER_OCX_OBJ.AddCustomButtonOnMenu(8, '关闭页面', true, 8, 80)
    }
  },

  // 增加自定义菜单
  MyCustomMenus: function () {
    TANGER_OCX_OBJ.AddCustomMenu2(0, '新建(&N)')
    // 增加一级菜单子菜单项目
    TANGER_OCX_OBJ.AddCustomMenuItem2(0, 0, -1, false, '新建WORD文档', false, 4050)
    TANGER_OCX_OBJ.AddCustomMenuItem2(0, 1, -1, false, '新建EXCEL文档', false, 4100)
    TANGER_OCX_OBJ.AddCustomMenuItem2(0, 2, -1, false, '新建PPT文档', false, 4150)

    this.AddButtonOnMenu()
  },

  // 从服务器磁盘目录打开文档
  OpenOfficeFromServerDir: function () {
    TANGER_OCX_OBJ.OpenFromURL(openurl)
  },

  // 从数据库打开文档
  OpenOfficeFromMysql: function () {
    TANGER_OCX_OBJ.OpenFromURL('OpenFromMysql.jsp?id=1')
  },

  // 从服务器项目相对路径打开文档
  OpenOfficeFromServer: function () {
    TANGER_OCX_OBJ.OpenFromURL('OfficeFile/head.doc')
  },

  // 从服务器项目相对目录打开PDF文档
  OpenPdfFromUrl: function () {
    TANGER_OCX_OBJ.OpenFromURL('OfficeFile/test.pdf')
  },

  // 从URL打开文档
  OpenOfficeFromURL: function () {
    TANGER_OCX_OBJ.OpenFromURL('OfficeFile/test.doc')
  },

  // 从本地打开文档
  OpenLocalFile: function () {
    TANGER_OCX_OBJ.ShowDialog(1)
  },

  // 保存文档到服务器磁盘目录
  SaveOfficeToServerDir: function () {
    var filename = 'mydoc.doc'
    var a = TANGER_OCX_OBJ.SaveToURL(
      saveurl, // 提交到的url地址
      'upLoadFile', // 文件域的id，类似<input type=file name=upLoadFile 中的name
      'p1=a&p2=b&p3=c', // 与控件一起提交的参数如："p1=a&p2=b&p3=c"
      filename, // 上传文件的名称，类似<input type=file 的value
      0, // 与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
      true)
    if (window.navigator.platform == 'Win32' || window.navigator.platform == 'Win64') {
      this.SaveToURL('', '', a)
    }
  },

  SaveOfficeToServerDir5: function () {
    var filename = 'mydoc.ofd'
    var a = TANGER_OCX_OBJ.SaveAsOFDToURL(
      saveurl, // 提交到的url地址
      'upLoadFile', // 文件域的id，类似<input type=file name=upLoadFile 中的name
      'p1=a&p2=b&p3=c', // 与控件一起提交的参数如："p1=a&p2=b&p3=c"
      filename, // 上传文件的名称，类似<input type=file 的value
      0, // 与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
      true)
    if (browser == 'IE') {
      TANGER_OCX_OBJ.ShowTipMessage('提示', this.trim(a))
    }
  },

  SaveOfficeToServerDir4: function () {
    var filename = 'mydoc.pdf'
    TANGER_OCX_OBJ.IsUseOfficeConvertDocToPDF = true
    var a = TANGER_OCX_OBJ.PublishAsHTMLToURL(
      saveurl, // 提交到的url地址
      'upLoadFile', // 文件域的id，类似<input type=file name=upLoadFile 中的name
      'p1=a&p2=b&p3=c', // 与控件一起提交的参数如："p1=a&p2=b&p3=c"
      filename, // 上传文件的名称，类似<input type=file 的value
      0, // 与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
      true)
    if (browser == 'IE') {
      TANGER_OCX_OBJ.ShowTipMessage('提示', this.trim(a))
    }
  },

  SaveOfficeToServerDir3: function () {
    var filename = 'mydoc.html'
    var a = TANGER_OCX_OBJ.PublishAsHTMLToURL(
      saveurl, // 提交到的url地址
      'upLoadFile', // 文件域的id，类似<input type=file name=upLoadFile 中的name
      'p1=a&p2=b&p3=c', // 与控件一起提交的参数如："p1=a&p2=b&p3=c"
      filename, // 上传文件的名称，类似<input type=file 的value
      0, // 与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
      true)
    if (browser == 'IE') {
      TANGER_OCX_OBJ.ShowTipMessage('提示', this.trim(a))
    }
  },
  // 保存文档到服务器磁盘目录
  SaveOfficeToServerDir2: function () {
    var filename = 'mydoc.doc'
    var a = TANGER_OCX_OBJ.SaveAsOtherFormatToURL(
      5,
      saveurl, // 提交到的url地址
      'upLoadFile', // 文件域的id，类似<input type=file name=upLoadFile 中的name
      'p1=a&p2=b&p3=c', // 与控件一起提交的参数如："p1=a&p2=b&p3=c"
      filename, // 上传文件的名称，类似<input type=file 的value
      0, // 与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
      true)
    if (browser == 'IE') {
      TANGER_OCX_OBJ.ShowTipMessage('提示', this.trim(a))
    }
  },
  // 保存文档到数据库
  SaveOfficeToMysql: function () {
    var filename = '20150408001.doc'
    var a = TANGER_OCX_OBJ.SaveToURL(
      'http://192.168.0.105:1986/newdemo/server/SaveToMysql.jsp?id=' + '0', // 提交到的url地址
      'upLoadFile', // 文件域的id，类似<input type=file name=upLoadFile 中的name
      '', // 与控件一起提交的参数如："p1=a&p2=b&p3=c"
      '', // 上传文件的名称，类似<input type=file 的value
      0 // 与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
    )
    if (browser == 'IE') {
      TANGER_OCX_OBJ.ShowTipMessage('提示', this.trim(a))
    }
  },
  // 保存文档为PDF到服务器
  SaveAsPdfToUrl: function () {
    if (!TANGER_OCX_OBJ.IsPDFCreatorInstalled()) {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '请先安装PDFCreator！')
      return
    }
    try {
      var filename = '2.pdf'
      TANGER_OCX_OBJ.PublishAsPDFToURL(saveurl, 'upLoadFile', '', filename)
    } catch (e) {
      alert(e)
    }
  },
  // 保存文档为PDF到服务器
  SaveAsPdfToUrl2: function () {
    try {
      var filename = '2.pdf'
      if (window.navigator.platform.indexOf('Linux') == -1) {
        TANGER_OCX_OBJ.IsUseOfficeConvertDocToPDF = true
      }
      TANGER_OCX_OBJ.PublishAsPDFToURL(saveurl, 'upLoadFile', '', filename)
    } catch (e) {
      alert(e)
    }
  },

  SetBookMarksValut: function () {
    var bookmarks = TANGER_OCX_OBJ.Activedocument.Bookmarks
    var list = document.getElementsByTagName('input')
    var strData = ''
    for (var i = 0; i < list.length && list[i]; i++) {
      if (list[i].type == 'text') {
        if (bookmarks.Exists(list[i].id)) {
          TANGER_OCX_OBJ.SetBookMarkValue(list[i].id, list[i].value)
        }
      }
    }
  },

  // 设置书签的值
  SetBookMarkValue: function () {
    var myDate = new Date()
    TANGER_OCX_OBJ.SetBookmarkValue('wenhao', 'NTKO-2015001')
    TANGER_OCX_OBJ.SetBookmarkValue('biaoti', '关于上海办事处成立的通知')
    TANGER_OCX_OBJ.SetBookmarkValue('luokuan', '重庆XX科技有限公司')
    TANGER_OCX_OBJ.SetBookmarkValue('riqi', myDate.getFullYear() + '-' + myDate.getMonth() + '-' + myDate.getDate())
  },

  // 获取书签的值
  GetBookMarkValue: function () {
    var mybokmarks = TANGER_OCX_OBJ.ActiveDocument.BookMarks
    var content = ''
    for (var i = 1; i <= mybokmarks.count; i++) {
      content += '书签名称：' + mybokmarks.Item(i).Name + '---书签内容：' + TANGER_OCX_OBJ.GetBookmarkValue(i) + '\r\n'
    }
    alert(content)
  },

  AddPicWaterMarkforExcel () {
    TANGER_OCX_OBJ.Activate(true)
    var doc = TANGER_OCX_OBJ.ActiveDocument
    doc.Application.ActiveWindow.View = 3
    var sheetCount = TANGER_OCX_OBJ.ActiveDocument.Application.Sheets.Count
    for (i = 1; i <= sheetCount; i++) {
      var sht = TANGER_OCX_OBJ.ActiveDocument.Application.Sheets(i)
      var ps = sht.PageSetup
      ps.CenterHeaderPicture.FileName = this.getUrl() + 'test.png'
      ps.CenterHeader = '\r\n\r\n\r\n\r\n\r\n\r\n&G'
      ps.CenterHeaderPicture.Brightness = 0.8
    }
    doc.Application.ActiveWindow.View = 1
  },

  // 是否显示书签标记
  IsShowBookMark: function () {
    TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.ActivePane.View.ShowBookmarks = !TANGER_OCX_OBJ.ActiveDocument.ActiveWindow.ActivePane.View.ShowBookmarks
  },

  // 电子印章EKEY盖章
  AddEkeySecSign: function () {
    var uName = 'NTKO'
    if (IsFileOpened) {
      if (TANGER_OCX_OBJ.doctype == 1 || TANGER_OCX_OBJ.doctype == 2) {
        try {
          var doc = TANGER_OCX_OBJ.ActiveDocument
          var sel = doc.Application.Selection
          if (!doc.Bookmarks.Exists('luokuan')) {
            alert('盖章位置不存在，用印操作失败！')
            return
          }
          // 获取盖章书签的起始位置
          sel.Goto(-1, 0, 0, 'luokuan')
          var bke = sel.Range.End
          var bks = sel.Range.Start
          // 获取书签的横向中心位置，并计算出像素值
          var cen = (bke - bks) / 2 + bks
          sel.SetRange(cen, cen)
          // 设置印章偏移值
          var mLeft = -45
          var mTop = -45
          // 从EKEY盖章
          TANGER_OCX_OBJ.AddSecSignFromEkey(uName, mLeft, mTop, 1, 2, false, true, true, false, '11111111', -1, false, false)
        } catch (error) {}
      } else {
        TANGER_OCX_OBJ.ShowTipMessage('提示', '不能在该类型文档中使用安全签名印章.')
      }
    }
  },

  // 演示通过印章接口控制印章
  SetSignprintMode: function () {
    if (IsFileOpened) {
      if (TANGER_OCX_OBJ.doctype == 1 || TANGER_OCX_OBJ.doctype == 2) {
        var ntkoocx = TANGER_OCX_OBJ
        var mydoc = ntkoocx.ActiveDocument
        var Shapes = mydoc.Shapes
        var con = 0
        for (var i = 1; i <= Shapes.Count; i++) {
          var curShape = Shapes(i)
          if ((curShape.TYPE == 12) && ('NTKO.SecSignControl'.toUpperCase() == curShape.OLEFormat.ClassType.toUpperCase())) {
            var ntkoSignObj = curShape.OLEFormat.Object // 得到印章对象
            ntkoSignObj.SetForceShowGray(true) // 使用印章的方法-强制变灰
            ntkoSignObj.RefreshCheckStatus() // 使用印章的方法-刷新印章状态
            ntkoSignObj.SetprintMode(1) // 使用印章的方法-设置打印属性
          }
        }
      } else {
        TANGER_OCX_OBJ.ShowTipMessage('提示', '没有文档处于编辑状态或不是支持的签章文档类型！')
      }
    }
  },

  // 自定义菜单栏触发事件--
  /* OnCustomButtonOnMenuCmd(btnPos, btnCaption, btnCmdid) {
    if (btnPos == 1) {
      TANGER_OCX_OBJ.ActiveDocument.Application.Selection.TypeText("追加内容");
    } else if (btnPos == 2) {
      this.addWaterMark("复印无效");
    } else if (btnPos == 3) {
      this.addWaterMarkPic(this.getUrl() + "test.png");
    } else if (btnPos == 4) {
      this.SetBookMarksValut();
    } else if (btnPos == 5) {
      this.ReplaceKeyWords();
    } else if (btnPos == 6) {
      this.ReplaceKeyWords2();
    } else if (btnPos == 7) {
      this.DelWaterPic();
    } else if (btnPos == 8) {
      if (TANGER_OCX_OBJ.FullScreenMode) {
        TANGER_OCX_OBJ.FullScreenMode = false;
      }
      window.opener = null;
      window.open('', '_self');
      window.close();
    }
  }, */

  // 增加文字水印
  addWaterMark: function (text) {
    try {
      var ActiveDocument = TANGER_OCX_OBJ.ActiveDocument
      // ActiveDocument.Sections(1).Range.Select();
      ActiveDocument.ActiveWindow.ActivePane.View.SeekView = 9 // wdSeekCurrentPageHeader
      ActiveDocument.Application.ScreenUpdating = false
      var Selection = ActiveDocument.Application.Selection
      for (var i = 1; i <= Selection.HeaderFooter.Shapes.Count; i++) {
        if (Selection.HeaderFooter.Shapes.Item(i).Name == 'watermarkpic') {
          return
        }
      }
      Selection.PageSetup.DifferentFirstpageHeaderFooter = -1 ? Selection.PageSetup.DifferentFirstpageHeaderFooter = false : '' // 取消首页不同
      Selection.PageSetup.OddAndEvenPagesHeaderFooter == -1 ? Selection.PageSetup.OddAndEvenPagesHeaderFooter = false : '' // 取消奇偶页不同
      Selection.HeaderFooter.Shapes.AddTextEffect(0, text, '宋体', 1, false, false, 0, 0).select()
      Selection.ShapeRange.Name = 'watermarkpic'
      // Selection.HeaderFooter.Shapes(1).Select();
      // Selection.ShapeRange.TextEffect.NormalizedHeight = false;
      // Selection.ShapeRange.Name = "msoTextEffect1";
      Selection.ShapeRange.Line.Visible = false
      Selection.ShapeRange.Fill.Visible = true
      Selection.ShapeRange.Fill.Solid()
      Selection.ShapeRange.Fill.ForeColor.RGB = 12345
      Selection.ShapeRange.Fill.Transparency = 0.5
      Selection.ShapeRange.Rotation = 315
      Selection.ShapeRange.LockAspectRatio = true
      Selection.ShapeRange.Height = ActiveDocument.Application.CentimetersToPoints(4.13)
      Selection.ShapeRange.Width = ActiveDocument.Application.CentimetersToPoints(16.52)
      Selection.ShapeRange.WrapFormat.AllowOverlap = true
      Selection.ShapeRange.WrapFormat.Side = 3 // wdWrapNone
      Selection.ShapeRange.WrapFormat.Type = 3
      Selection.ShapeRange.RelativeHorizontalPosition = 0 // wdRelativeVerticalPositionMargin
      Selection.ShapeRange.RelativeVerticalPosition = 0 // wdRelativeVerticalPositionMargin
      Selection.ShapeRange.Left = -999995 // wdShapeCenter
      Selection.ShapeRange.Top = -999995 // wdShapeCenter
      ActiveDocument.ActiveWindow.ActivePane.View.SeekView = 0 // wdSeekMainDocument
      ActiveDocument.Application.ScreenUpdating = true
    } catch (err) {
      ActiveDocument.Application.ScreenUpdating = true
      alert('插入水印失败：' + err.description)
    }
  },

  DelWaterPic: function () {
    try {
      var ActiveDocument = TANGER_OCX_OBJ.ActiveDocument
      ActiveDocument.ActiveWindow.ActivePane.View.SeekView = 9 // wdSeekCurrentPageHeader
      var Selection = ActiveDocument.Application.Selection
      Selection.HeaderFooter.Shapes.Item('watermarkpic').Select()
      Selection.Delete()
      ActiveDocument.ActiveWindow.ActivePane.View.SeekView = 0 // wdSeekMainDocument
    } catch (err) {
      alert('删除水印失败：' + err.description)
    }
  },

  // 增加图片水印
  addWaterMarkPic (URL) {
    try {
      var ActiveDocument = TANGER_OCX_OBJ.ActiveDocument
      // ActiveDocument.Sections(1).Range.Select();
      ActiveDocument.ActiveWindow.ActivePane.View.SeekView = 9 // wdSeekCurrentPageHeader
      ActiveDocument.Application.ScreenUpdating = false
      var Selection = ActiveDocument.Application.Selection
      Selection.HeaderFooter.Shapes.AddPicture(URL, false, true).Select()
      Selection.ShapeRange.Name = 'wordwatermakepic2'
      Selection.ShapeRange.PictureFormat.Brightness = 0.8
      Selection.ShapeRange.PictureFormat.Contrast = 0.5
      Selection.ShapeRange.LockAspectRatio = true
      Selection.ShapeRange.Height = ActiveDocument.Application.CentimetersToPoints(4.42)
      Selection.ShapeRange.Width = ActiveDocument.Application.CentimetersToPoints(4.92)
      Selection.ShapeRange.WrapFormat.AllowOverlap = true
      Selection.ShapeRange.WrapFormat.Side = 3
      Selection.ShapeRange.WrapFormat.Type = 3
      Selection.ShapeRange.RelativeHorizontalPosition = 0
      Selection.ShapeRange.RelativeVerticalPosition = 0
      Selection.ShapeRange.Left = -999995 // wdShapeCenter
      Selection.ShapeRange.Top = -999995 // wdShapeCenter
      ActiveDocument.ActiveWindow.ActivePane.View.SeekView = 0 // wdSeekMainDocument
      ActiveDocument.Application.ScreenUpdating = true
    } catch (err) {
      ActiveDocument.Application.ScreenUpdating = true
      alert('插入水印失败：' + err.description)
    }
  },

  // 自定义菜单触发
  OnCustomMenuCmd2 (menuPos, submenuPos, subsubmenuPos, menuCaption, menuID) {
    if (menuID == 4050) {
      this.CreateNewOffice('Word.Document')
    } else if (menuID == 4100) {
      this.CreateNewOffice('Excel.Sheet')
    } else if (menuID == 4150) {
      this.CreateNewOffice('PowerPoint.Show')
    } else {
      TANGER_OCX_OBJ.ShowTipMessage('提示', '第' + menuPos + ',' + submenuPos + ',' + subsubmenuPos + '个菜单项,menuID=' + menuID + ',菜单标题为"' + menuCaption + '"的命令被执行.')
    }
  },

  // 获取文档名称
  GetFileName (filepath) {
    if (filepath != '') {
      var names = filepath.split('\\')
      return names[names.length - 1]
    }
  },

  serchKeyWords (keys) {
    var sel = TANGER_OCX_OBJ.ActiveDocument.Application.Selection
    var pagenum = TANGER_OCX_OBJ.ActiveDocument.Application.Selection.Information(3)
    sel.Find.ClearFormatting()
    sel.Find.Text = keys
    sel.Find.Replacement.Text = ''
    sel.Find.Forward = true
    sel.Find.Wrap = 1
    sel.Find.Format = false
    sel.Find.MatchCase = false
    sel.Find.MatchWholeWord = false
    sel.Find.MatchByte = true
    sel.Find.MatchAllWordForms = false
    sel.Find.MatchSoundsLike = false
    sel.Find.MatchAllWordForms = false
    while (Execute()) {
      var bke = sel.Range.End
      var bks = sel.Range.Start
      var cen = (bke - bks) / 2 + bks
      sel.SetRange(cen, cen)
      sel.InsertAfter(pagenum)
    }
    TANGER_OCX_OBJ.ActiveDocument.Application.Selection.Homekey(6) // 回到文档首页
  },

  AddAttachFile: function () {
    TANGER_OCX_OBJ.DeleAllFileFromUploadFileAttachFileList() // 删除上次选择的文件 ，也可以不删根据流程需求
    // DeleFileFromUploadFileAttachFileList(ByVal FileName) 此方法可以删除指定的文件
    TANGER_OCX_OBJ.AddFileToUploadFileAttachFileList('attachFile[]', true, '*')
    var count = TANGER_OCX_OBJ.GetUploadFileAttachFileCount()
    var filepaths = ''
    for (var i = 1; i <= count; i++) {
      filepaths += TANGER_OCX_OBJ.GetUploadFileAttachItemFile(i) + ';'
    }
    document.getElementById('FileUploadText').value = filepaths
  },

  ReplaceKeyWords: function () {
    TANGER_OCX_OBJ.ActiveDocument.Application.Selection.Find.Execute('行政部')
    TANGER_OCX_OBJ.ActiveDocument.Application.Selection.TypeText('祎重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司')
  },

  ReplaceKeyWords2: function () {
    var doc = TANGER_OCX_OBJ.ActiveDocument // TANGER_OCX_OBJ为控件对象
    doc.Application.Selection.Find.text = '行政部'
    var relpace = '重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司重庆软航科技有限公司'
    doc.Application.Selection.Find.Execute('行政部', false, false, false, false, false, true, 1, false, relpace, 2) // execute方法可参考word的api
  }

  /** -----------------------------以下未使用 结束-------------------------------------**/

}
